package com.atguigu.springmvc.utils;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springblade.core.tool.utils.DateUtil;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author : wenchao.long
 * @date : Created in 2020/11/05 9:08 周四
 * @description :
 */
public class JsonUtils {

    public static String getJson(Object obj) {
        ObjectMapper mapper = new ObjectMapper();

        if (obj instanceof Date) {
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            mapper.setDateFormat(new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN));
        }
        if (obj instanceof LocalDateTime) {
            LocalDateTime localDateTime = (LocalDateTime) obj;
            try {
                return mapper.writeValueAsString(localDateTime.format(DateUtil.DATETIME_FORMATTER));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return null;
    }

}
